/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.config.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.icinfo.cloud.provider.punish.config.dto.ConfigPaymentSourceBaseinfoDto;
import com.icinfo.cloud.provider.punish.config.mapper.ConfigPaymentSourceBaseinfoMapper;
import com.icinfo.cloud.provider.punish.config.model.ConfigPaymentSourceBaseinfo;
import com.icinfo.cloud.provider.punish.config.service.IConfigPaymentSourceBaseinfoService;
import com.icinfo.cloud.provider.punish.config.vo.ConfigPaymentSourceInfoVo;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.tools.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.*;

/**
 * 描述: 支付基础信息同步表 config_payment_source_baseinfo 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2023年02月17日
 */
@Service
@Slf4j
public class ConfigPaymentSourceBaseinfoServiceImpl extends MyBatisServiceSupport implements IConfigPaymentSourceBaseinfoService {
    /**
     * 日志记录器
     */
    private static final Logger logger = LoggerFactory.getLogger(ConfigPaymentSourceBaseinfoServiceImpl.class);

    @Autowired
    private ConfigPaymentSourceBaseinfoMapper configPaymentSourceBaseinfoMapper;

    @Value("${paymentUnified.url}")
    private String paymentUnifiedUrl;
    @Value("${paymentUnified.uri.getBasicResultInfoList}")
    private String getBasicResultInfoListUrl;

    /**
     * 【V1.11.0】描述：根据参数获取公共支付基础信息-来自支付平台
     *
     * @param queryDto
     * @return
     * @date 2023-02-17
     * @author tianrunjia
     */
    @Override
    public List<ConfigPaymentSourceBaseinfo> doGetConfigPaymentSourceInfoByParam(ConfigPaymentSourceBaseinfoDto queryDto) {
        String queryColumn = "";
        String whereColumn = "channel_no = '330000022' and sync_batch = '" + DateUtils.formatDate(new Date(), "yyyyMMdd") + "' ";
        if (StringUtils.isNotEmpty(queryDto.getRegiCode())) {
            queryColumn = " distinct regi_name,ente_code ";
            whereColumn = whereColumn + " and regi_code = '" + queryDto.getRegiCode() + "' ";
            if (StringUtils.isNotEmpty(queryDto.getEnteCode())) {
                queryColumn = queryColumn + " ,ente_name ";
                whereColumn = whereColumn + " and ente_code = '" + queryDto.getEnteCode() + "' ";
                if (StringUtils.isNotEmpty(queryDto.getEnteName())) {
                    queryColumn = queryColumn + " ,chit_code,chit_name ";
                    whereColumn = whereColumn + " and ente_name = '" + queryDto.getEnteName() + "' ";
                }
            }
            return configPaymentSourceBaseinfoMapper.selectConfigPaymentSourceBaseinfoByParmam(queryColumn, whereColumn);
        } else {
            return null;
        }

    }

    /**
     * 描述：同步支付基础信息
     *
     * @return 支付基础信息列表
     * @author lilihao
     * @date 2023/2/24 15:45
     */
    @Override
    public void syncPaymentBaseInfoListBatch(String channelNo) {
        log.info("syncPaymentBaseInfoList start... channelNo:{}", channelNo);
        Map<String, Object> paramMap = new HashMap<>(8);
        paramMap.put("channelNo", channelNo);
        paramMap.put("checkCode", "");

        try {
            String result = HttpUtil.post(paymentUnifiedUrl + getBasicResultInfoListUrl, JSONUtil.toJsonStr(paramMap));
            if (!ObjectUtils.isEmpty(result)) {
                JSONObject jsonObject = JSONUtil.toBean(result, JSONObject.class);
                JSONArray jsonArray = jsonObject.getJSONArray("data");
                if (!ObjectUtil.isEmpty(jsonArray) && jsonArray.size() > 0) {
                    //1.批量插入历史记录
                    String syncBatch = DateUtil.today().replace("-", "");
                    Date syncTime = new Date();
                    List<ConfigPaymentSourceBaseinfo> list = new ArrayList<>();
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject json = jsonArray.getJSONObject(i);
                        JSONArray list1 = json.getJSONArray("list");
                        for (int j = 0; j < list1.size(); j++) {
                            ConfigPaymentSourceBaseinfo configPaymentSourceBaseInfo = JSONUtil.toBean(json, ConfigPaymentSourceBaseinfo.class);
                            JSONObject jsonObject1 = list1.getJSONObject(j);
                            String chitCode = jsonObject1.getStr("chitCode");
                            String chitName = jsonObject1.getStr("chitName");
                            configPaymentSourceBaseInfo.setChitCode(chitCode);
                            configPaymentSourceBaseInfo.setChitName(chitName);
                            configPaymentSourceBaseInfo.setSyncTime(syncTime);
                            configPaymentSourceBaseInfo.setSyncBatch(syncBatch);
                            configPaymentSourceBaseInfo.setId(IdUtil.simpleUUID());
                            list.add(configPaymentSourceBaseInfo);
                            if (list.size() == 2000) {
                                configPaymentSourceBaseinfoMapper.insertList(list);
                                list.clear();
                            }
                        }
                    }
                    if (CollectionUtil.isNotEmpty(list)) {
                        configPaymentSourceBaseinfoMapper.insertList(list);
                    }
                } else {
                    log.warn("syncPaymentBaseInfoList response data is null");
                }
            } else {
                log.warn("syncPaymentBaseInfoList response is null");
            }
        } catch (
                Exception e) {
            e.printStackTrace();
            log.warn(e.getMessage());
        }
    }
}